<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>流程配置</title>
    <link rel="stylesheet" href="../../../assert/css/font.css" th:href="@{/assert/css/font.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap.min.css" th:href="@{/assert/css/bootstrap.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/plugin/chosen/chosen.css"
          th:href="@{/assert/css/plugin/chosen/chosen.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-table.css" th:href="@{/assert/css/bootstrap-table.css}"/>
    <link href="../../../assert/css/animate.min.css" rel="stylesheet" th:href="@{/assert/css/animate.min.css}">
    <link href="../../../assert/css/plugin/toastr/toastr.min.css" rel="stylesheet"
          th:href="@{/assert/css/plugin/toastr/toastr.min.css}">
    <link href="../../../assert/css/plugin/jsTree/themes/default/style.css" rel="stylesheet"
          th:href="@{/assert/css/plugin/jsTree/themes/default/style.css}">
    <link href="../../../assert/css/loaders.css" rel="stylesheet"
          th:href="@{/assert/css/loaders.css}">
    <link rel="stylesheet" href="../../../assert/css/bootstrapValidator.css"
          th:href="@{/assert/css/bootstrapValidator.css}"/>
    <link rel="stylesheet" href="../../../assert/css/jquery-ui.css" th:href="@{/assert/css/jquery-ui.css}"/>
    <link href="../../../assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css" rel="stylesheet"
          th:href="@{/assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css}"/>
    <link rel="stylesheet" href="../../../assert/css/index.css" th:href="@{/assert/css/index.css(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"/>
    <style>
        .search_group label.control-label{
            width:85px;
        }
    </style>
</head>
<body>
<div class="wrapper wrapper-content">
    <div class="ibox">
        <div class="tools_bar">
            <div class="pull-left">
                <a href="#" class="btn btn-default active" id="btnSearch" title="隐藏查询条"><i class="fa fa-filter"></i> 隐藏</a>
                <a href="#" class="btn btn-default active" id="refresh"><i class="fa fa-refresh"></i> 刷新</a>
                <a href="#" class="btn btn-default active" id="btnAdd" title="添加流程配置"><i class="fa fa-plus"></i>
                    添加</a>
                <a href="#" class="btn btn-default active" id="btnEdit" title="编辑流程配置"><i class="fa fa-pencil"></i>
                    编辑</a>
                <a href="#" class="btn btn-default active" id="btnDel" title="删除流程配置"><i class="fa fa-trash"></i>
                    删除</a>
            </div>
        </div>
        <div class="search on">
            <div class="search_group">
                <label class="control-label">审批数据：</label>
                <div class="control-inline">
                    <select type="text" id="auditData" value="" class="form-control search_input"></select>
                </div>
            </div>
            <div class="search_group">
                <label class="control-label">提交角色：</label>
                <div class="control-inline">
                    <select type="text" id="submitRole" value="" class="form-control search_input"></select>
                </div>
            </div>
            <div class="search_group">
                <label class="control-label">审批角色：</label>
                <div class="control-inline">
                    <select type="text" id="auditRole" value="" class="form-control search_input"></select>
                </div>
            </div>
            <div class="search_group">
                <label class="control-label">创建时间：</label>
                <div class="control-inline">
                    <input placeholder="开始日期" class="form-control layer-date search_input" id="startCreat" autocomplete="off"> -
                    <input placeholder="结束日期" class="form-control layer-date search_input" id="endCreat" autocomplete="off">
                </div>
            </div>
            <div class="search_group">
                <label class="control-label" style="width:114px;">最后更新时间：</label>
                <div class="control-inline">
                    <input placeholder="开始日期" class="form-control layer-date search_input" id="startUpdate" autocomplete="off"> -
                    <input placeholder="结束日期" class="form-control layer-date search_input" id="endUpdate" autocomplete="off">
                </div>
            </div>


            <div class="search_group">
                <button id="search" class="btn  btn-primary">查询</button>
                <button id="reset" class="btn  btn-default">重置</button>
                <button id="export" class="btn  btn-default hidden">导出</button>
            </div>
        </div>
        <table id="myTable"></table>
    </div>
</div>
<!--添加审核流程配置模态框-->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" style="width:600px !important;">
        <div class="modal-content">
            <form method="post" class="form-horizontal styleForm" id="addForm">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span
                            class="sr-only">Close</span></button>
                    <h4 class="modal-title">添加审核流程配置</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="" class="col-sm-3 control-label"><span class="respan">*</span>审批数据:</label>
                        <div class="col-sm-8">
                            <select class="form-control" name="code" id="auditDataAdd"></select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-sm-3 control-label">提交角色:</label>
                        <div class="col-sm-8">
                            <select class="form-control" name="code" id="submitRoleAdd"></select>
                        </div>
                    </div>
                    <div class="auditRoleBox">
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label"><span class="respan">*</span>1审批角色:</label>
                            <div class="col-sm-8">
                                <select class="form-control auditRoleAdd" name="code"></select><span class="fa fa-plus plusAddBtn"></span>
                                <div class="form-content radio_box">
                                    <div class="radio"> <input type="radio" value="1" name="auditRole" checked>省内</div>
                                    <div class="radio"> <input type="radio" value="0" name="auditRole">集团</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <span class="maxAuditNum"></span>
                    <button type="button" class="btn btn-primary" id="addSave">保存</button>
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--编辑审核流程配置模态框-->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" style="width:600px !important;">
        <div class="modal-content">
            <form method="post" class="form-horizontal styleForm" id="editForm">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span
                            class="sr-only">Close</span></button>
                    <h4 class="modal-title">编辑审核流程配置</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="" class="col-sm-3 control-label"><span class="respan">*</span>审批数据:</label>
                        <div class="col-sm-8">
                            <select class="form-control" name="code" id="auditDataEdit"></select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-sm-3 control-label">提交角色:</label>
                        <div class="col-sm-8">
                            <select class="form-control" name="code" id="submitRoleEdit"></select>
                        </div>
                    </div>
                    <div class="auditRoleBox">
                        <div class="form-group">
                            <label for="" class="col-sm-3 control-label"><span class="respan">*</span>1审批角色:</label>
                            <div class="col-sm-8">
                                <select class="form-control auditRoleAdd" name="code"></select><span class="fa fa-plus plusAddBtn"></span>
                                <div class="form-content radio_box">
                                    <div class="radio"> <input type="radio" value="1" name="auditRole" checked>省内</div>
                                    <div class="radio"> <input type="radio" value="0" name="auditRole">集团</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <span class="maxAuditNum"></span>
                    <button type="button" class="btn btn-primary" id="editSave">保存</button>
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!--删除审核数据确认框-->
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span
                            class="sr-only">Close</span></button>
                    <h4 class="modal-title">删除</h4>
                </div>
                <div class="modal-body">
                    <div style="text-align: center"><span class="fa fa-question-circle"></span><span
                            id="delName"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="delBtn">确定</button>
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>
<a id="basePath" th:href="@{/}"></a>
<input type="text" id="classify" class="hidden">
<input type="text" id="proSelectModal" class="hidden">
<script src="../../../assert/js/jquery.js" th:src="@{/assert/js/jquery.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap.min.js" th:src="@{/assert/js/bootstrap.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/plugin/bootstrap-table/bootstrap-table.min.js" th:src="@{/assert/js/plugin/bootstrap-table/bootstrap-table.min.js}"></script>
<script src="../../../assert/js/bootstrapValidator.js" th:src="@{/assert/js/bootstrapValidator.js}"></script>
<script src="../../../assert/js/plugin/toastr/toastr.min.js"
        th:src="@{/assert/js/plugin/toastr/toastr.min.js}"></script>
<script src="../../../assert/js/base.js" th:src="@{/assert/js/base.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/jquery-ui.min.js" th:src="@{/assert/js/jquery-ui.min.js}"></script>
<script src="../../../assert/js/plugin/layer/laydate/laydate.js"
        th:src="@{/assert/js/plugin/layer/laydate/laydate.js}"></script>
<script src="../../../assert/js/changeTime.js" th:src="@{/assert/js/changeTime.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/plugin/jsTree/jstree.min.js"
        th:src="@{/assert/js/plugin/jsTree/jstree.min.js}"></script>
<script src="../../../assert/js/plugin/chosen/chosen.jquery.js"
        th:src="@{/assert/js/plugin/chosen/chosen.jquery.js}"></script>
<script src="../../../assert/js/common.js" th:src="@{/assert/js/common.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/jqxcore.js"
        th:src="@{/assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/jqxcore.js}"></script>
<script src="../../../assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/jqxvalidator.js"
        th:src="@{/assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/jqxvalidator.js}"></script>
<script>
    //项目名称
    var basePath = $("#basePath").attr("href");
    var json = [];
    //    页面主表格
    var TableInit = function () {
        var oTableInit = new Object();
        var url = basePath + "/rest/approval/config-page";
        var height = ($(window).height() -$(".tools_bar").height()-9-$(".search").height()-40);
        //初始化Table
        oTableInit.Init = function () {
            $('#myTable').bootstrapTable({
                url: url,         //请求后台的URL（*）
                method: 'post',                      //请求方式（*）
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                height:height,
                sortable: false,                     //是否启用排序
//                sortName: "provinceCode", //排序方式
//                sortOrder: "asc",
                pagination: true,    //排序方式
                queryParams: oTableInit.queryParams,//传递参数（*）
                responseHandler: function (res) {
                    if (res.code != 0) {
                        toastrCog.error(res.msg, 3000);
                    }
                    return {
                        "total": res.count,//总页数
                        "rows": res.data   //数据
                    };
                },
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                contentType: "application/json",
                strictSearch: true,
                showColumns: false,                  //是否显示所有的列
                showRefresh: false,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "no",                     //每一行的唯一标识，一般为主键列
                showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,
                cellStyle: {
                    css: {"background-color": "#fff"}
                },//是否显示父子表
                columns: [
                    {
                        checkbox: true, // 显示一个勾选框
                        align: 'center' // 居中显示
                    },
                    {
                        align: "center",
                        halign: "center",
                        title: '序号',//标题  可不加
                        width: 60,
                        field: 'id',
                        formatter: function (value, row, index) {
                            var getOptions = $("#myTable").bootstrapTable('getOptions');
                            var pagenum = getOptions.pageNumber;
                            var pagesize = getOptions.pageSize;
                            var st = (pagenum - 1) * pagesize;
                            return (st + index + 1) + "";
                        }
                    },
                    {
                        align: "center",
                        halign: "center",
                        field: 'dataname',
                        title: '审批数据'
                    },
                    {
                        align: "center",
                        halign: "center",
                        field: 'lineuser',
                        title: '提交角色',
//                        sortable: true,
                    },
                    {
                        align: "center",
                        halign: "center",
                        field: 'approvalRole',
                        title: '审批角色',
//                        sortable: true,
                        formatter:function(value, row, index){
                           var rels= row.rels;
                           var str="";
                           for(var i=0;i<rels.length;i++){
                               var approle=rels[i].approle;
                               var number=rels[i].number;
                               str+=number+":"+approle;
                               if(i<(rels.length-1)){
                                   str+="<span class='fa fa-angle-double-right' style='font-size: 16px;padding: 0 7px;'></span>";
                               }
                           }
                            return str
                        }
                    },{
                        align: "center",
                        halign: "center",
                        field: 'inputtime',
                        title: '创建时间',
//                        sortable: true,
//                        sortName:"onsetTime",
                        formatter: function (value, row, index) {
                            return dateFormatUtil(value);
                        }
                    }, {
                        align: "center",
                        halign: "center",
                        field: 'lastupdatetime',
                        title: '最后更新时间',
//                        sortName:"lastUpdateTime",
//                        sortable: true,
                        formatter: function (value, row, index) {
                            return dateFormatUtil(value);
                        }
                    }
                ],
                onLoadSuccess: function (data) {  //加载成功时执行
                    resize.me();
                    if (!data.rows||data.rows.length == 0) {
                        var src=basePath+"/assert/image/nodata.png";
                        $("#myTable .no-records-found").find("td").html('<img src="'+src+'" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                    }
                },
                onLoadError: function () {  //加载失败时执行
                    var src=basePath+"/assert/image/nodata.png";
                    $("#myTable .no-records-found").find("td").html('<img src="'+src+'" th:src="@{/assert/image/nodata.png}" style="width:165px;" alt="">');
                },
                formatLoadingMessage: function () {
                    return '<div class="loaded">' +
                        '<div class="loader">' +
                        '<div class="loader-inner line-scale-pulse-out">' +
                        '<div></div>' +
                        '<div></div>' +
                        '<div></div>' +
                        '<div></div>' +
                        '<div></div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div>请稍等，数据正在加载中...</div>';
                }
            });
        };
        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                pageNum: params.offset/params.limit,   //页面大小
                pageSize: params.limit,
//                sortName: this.sortName,
//                sortOrder: this.sortOrder,
                datacode: $("#auditData").val(),
                submitterRole: $("#submitRole").val(),
                approvalRole: $("#auditRole").val(),
                inputtimebegin: $("#startCreat").val(),
                inputtimeend: $("#endCreat").val(),
                lastupdatetimebegin: $("#startUpdate").val(),
                lastupdatetimeend: $("#endUpdate").val()
            };
            return temp;
        };
        return oTableInit;
    };
    var resize = {
        init: function () {
            resize.me();
            $(window).resize(function () {
                resize.me();
            })
        },
        me: function () {
            var winW = $(window).width();
            var winH = $(window).height();
            $(".ibox").width(winW - 20);
            $(".ibox").height(winH - 20);
            bs.autoTableHeight($('#myTable'),winH -$(".tools_bar").height()-22-$(".search").height())
         }
    };
    var tools = {
        maxPeopleLength:null,
        roleArr:[],
        auditArr:[],
        init: function () {
            tools.getConfig();//获取最大审核人数
            tools.getAuditData();//获取所有审核数据
            tools.getRole();//获取所有角色
            tools.tabSearch();//是否显示查询条
            tools.search();//查询
            tools.enterSearch();//查询
            tools.reset();//重置
            tools.refresh();//刷新
            tools.addModel();//添加任务
            tools.editModel();
            tools.delModel();
            bs.dataTime("#startCreat","#endCreat");
            bs.dataTime("#startUpdate","#endUpdate");
            $("#addModal").on("hidden.bs.modal",function(){
                var form=$("#addForm");
                $("#auditDataAdd").val("").trigger("chosen:updated");
                $("#submitRoleAdd").val("").trigger("chosen:updated");
                form.find(".auditRoleBox .form-group").eq(0).find(".auditRoleAdd").val("").trigger("chosen:updated");
                form.find(".auditRoleBox .form-group").eq(0).find(".radio").val(1);
                form.find(".auditRoleBox .form-group").eq(0).find(".plusAddBtn").show();
                form.find(".auditRoleBox .form-group:gt(0)").remove();
//                tools.hideLabel(form,'#dataCodeAdd');
//                tools.hideLabel(form,'#dataNameAdd');
            });
            $("#editModal").on("hidden.bs.modal",function(){
                var form=$("#editForm");
//                tools.hideLabel(form,'#dataCodeEdit');
//                tools.hideLabel(form,'#dataNameEdit');
            });
        },
        getConfig: function () {
            var maxNum= bs.getSysConfig("AUDIT_PEOPLE_NUM");
            var num=5;
            if(maxNum){
                num=maxNum.value
            }
            tools.maxPeopleLength= num;
            $(".maxAuditNum").html("最大审批次数："+num);
        },
        getAuditData:function(){
            $.ajax({
                type: "post",
                url: basePath + "/rest/approval/data-list",
                dataType: "json",
                success: function (data) {
                    var data=data.data;
                    tools.auditArr.push({"name":"请选择","value":""});
                    if(data && data.length>0){
                        for(var i=0;i<data.length;i++){
                            var obj={};
                            obj.name=data[i].dataname;
                            obj.value=data[i].datacode;
                            tools.auditArr.push(obj)
                        }
                    }
                    bs.selectDownNoDisabled($("#auditData"),tools.auditArr,"");
                    bs.selectDownNoDisabled($("#auditDataAdd"),tools.auditArr,"","100%");
                    bs.selectDownNoDisabled($("#auditDataEdit"),tools.auditArr,"","100%");
                }
            })
        },
        getRole:function(){
            $.ajax({
                type: "post",
                url: basePath + "/rest/role/getAllRole",
                dataType: "json",
                success: function (data) {
                    tools.roleArr.push({"name":"请选择","value":""});
                    if(data && data.length>0){
                        for(var i=0;i<data.length;i++){
                            var obj={};
                            obj.name=data[i].name;
                            obj.value=data[i].id;
                            tools.roleArr.push(obj)
                        }
                    }
                    bs.selectDownNoDisabled($("#submitRole"),tools.roleArr,"");
                    bs.selectDownNoDisabled($("#auditRole"),tools.roleArr,"");
                    bs.selectDownNoDisabled($("#submitRoleAdd"),tools.roleArr,"","100%");
                    bs.selectDownNoDisabled($("#submitRoleEdit"),tools.roleArr,"","100%");
                    bs.selectDownNoDisabled($(".auditRoleAdd"),tools.roleArr,"","100%");
                }
            })
        },
        hideLabel:function(form,input){
            form.jqxValidator('hideHint', input);
        },
        selectChange:function($elem,$input){
            $elem.on("change", function (event, sel) {
                $input.val(sel.selected);
                if (sel.selected == "") {
                    $input.next().html("").css("display", "none !important");
                }
            });
        },
        tipShow: function () {
            $(".tipInput").hover(function () {
                $(this).find(".tip").removeClass("hidden")
            }, function () {
                $(this).find(".tip").addClass("hidden")
            })
        },
        tabSearch: function () {
            var search = $(".search");
            $("#btnSearch").on("click", function () {
                if (search.hasClass("on")) {
                    search.slideUp();
                    search.removeClass("on");
                    $("#btnSearch").html('<i class="fa fa-filter"></i> 查询').attr("title", "显示查询条");
                } else {
                    search.slideDown();
                    search.addClass("on");
                    $("#btnSearch").html('<i class="fa fa-filter"></i> 隐藏').attr("title", "隐藏查询条");
                }

            });
        },
        search: function () {
            $("#search").on("click", function () {
                tools.tableRefresh();
            })
        },
        enterSearch: function () {
            $("body").on("keyup", function (e) {
                var code = e.charCode || e.keyCode;
                if (code == 13) {
                    //此处编写用户敲回车后的代码
                    tools.tableRefresh();
                }
            })
        },
        tableRefresh: function () {
            $("#myTable").bootstrapTable('refreshOptions', {pageNumber:1});
            $("#myTable").bootstrapTable('refresh');
        },
        reset: function () {
            $("#reset").on("click", function () {
                bs.resetSearch($(".search"));
                if($("#laydate_box").length>0){
                    bs.resetTimeElems("#startCreat","#endCreat","#startUpdate","#endUpdate");
                }
                tools.tableRefresh();
            })
            $("#resetModel").on("click",function(){
                $("#classify").val("");
                $("#proSelectModal").val("");
                $("#jstree").jstree("deselect_all", true);
                $("#modelTableWin").bootstrapTable('refresh');
            })
        },
        resetSelect: function ($obj) {
            $obj.val("");
            $obj.trigger("chosen:updated");
        },
        refresh: function () {
            $("#refresh").on("click", function () {
                $("#myTable").bootstrapTable('refresh');
            })
        },
        addModel: function () {
            $("#addModal").on("hide.bs.modal", function () {
                $('#addForm')[0].reset();
            });
            $("#btnAdd").on("click", function () {
                $("#addModal").modal("show");
            });
            $("#addSave").on("click", function () {
                if($("#auditDataAdd").val()==""){
                    toastrCog.error("请选择审核数据！",1000)
                }else{
                    var str="";
                    $("#addForm .auditRoleAdd").each(function(){
                        if($(this).val()==""){
                            str+="0"
                        }
                    });
                    if(str.indexOf("0")>-1){
                        toastrCog.error("请选择审批角色",1000)
                    }else{
                        var auditArr=[];
                        $("#addForm .auditRoleAdd").each(function(){
                            var index=$(this).parents(".form-group").index()+1;
                            var obj={};
                            obj.number=index
                            obj.approle=bs.getXInY(tools.roleArr,"name","value",$(this).val());
                            obj.approleid=$(this).val();
                            obj.sameprovince=$(this).parents(".form-group").find("input[type='radio']:checked").val();
                            obj.islast=0;
                            if(index==$("#addForm .auditRoleBox .form-group").length){
                                obj.islast=1;
                            }
                            auditArr.push(obj);
                        });
                        $.ajax({
                            type: "post",
                            url: basePath + "/rest/approval/config-add",
                            dataType: "json",
                            contentType: "application/json",
                            data: JSON.stringify({
                                datacode: $("#auditDataAdd").val(),
                                dataname: bs.getXInY(tools.auditArr,"name","value",$("#auditDataAdd").val()),
                                linenumber: $("#submitRoleAdd").val(),
                                lineuser:bs.getXInY(tools.roleArr,"name","value",$("#submitRoleAdd").val()),
                                rels:auditArr
                            }),
                            success: function (data) {
                                if (data.code == 0) {
                                    $("#myTable").bootstrapTable('refresh');
                                    toastrCog.success(data.msg, 1000)
                                } else {
                                    toastrCog.error(data.msg, 3000)
                                }
                                $("#addModal").modal("hide");
                            }
                        })
                    }
                }
            });
        },
        editModel: function () {
            $("#editModal").on("hide.bs.modal", function () {

            });
            $("#btnEdit").on("click", function () {
                var selectArr = $("#myTable").bootstrapTable("getSelections");
                if (selectArr.length <= 0) {
                    toastrCog.error("请选择要编辑的数据！", 3000);
                } else if (selectArr.length > 1) {
                    toastrCog.error("请选择一条要编辑的数据！", 3000);
                } else {
                    $("#editModal").modal("show");
                    var editBox=$("#editForm .auditRoleBox");
                    editBox.html("");
                    var rels=selectArr[0].rels;
                    $("#auditDataEdit").val(selectArr[0].datacode).trigger("chosen:updated");
                    $("#submitRoleEdit").val(selectArr[0].linenumber).trigger("chosen:updated");
                    for(var i=0;i<rels.length;i++){
                        var value=rels[i].approleid;
                        var sameprovince=rels[i].sameprovince;
                        role.appendRole(editBox,value,sameprovince);
                    }
                    $("#editModal").attr("data-id",selectArr[0].id);
                }
            });
            $("#editSave").on("click", function () {
                if($("#auditDataEdit").val()==""){
                    toastrCog.error("请选择审核数据！",1000)
                }else{
                    var str="";
                    $("#editForm .auditRoleAdd").each(function(){
                        if($(this).val()==""){
                            str+="0"
                        }
                    });
                    if(str.indexOf("0")>-1){
                        toastrCog.error("请选择审批角色",1000)
                    }else{
                        var auditArr=[];
                        $("#editForm .auditRoleAdd").each(function(){
                            var index=$(this).parents(".form-group").index()+1;
                            var obj={};
                            obj.number=index
                            obj.approle=bs.getXInY(tools.roleArr,"name","value",$(this).val());
                            obj.approleid=$(this).val();
                            obj.sameprovince=$(this).parents(".form-group").find("input[type='radio']:checked").val();
                            obj.islast=0;
                            if(index==$("#editForm .auditRoleBox .form-group").length){
                                obj.islast=1;
                            }
                            auditArr.push(obj);
                        });
                        $.ajax({
                            type: "post",
                            url: basePath + "/rest/approval/config-update",
                            dataType: "json",
                            contentType: "application/json",
                            data: JSON.stringify({
                                id:$("#editModal").attr("data-id"),
                                datacode: $("#auditDataEdit").val(),
                                dataname: bs.getXInY(tools.auditArr,"name","value",$("#auditDataEdit").val()),
                                linenumber: $("#submitRoleEdit").val(),
                                lineuser:bs.getXInY(tools.roleArr,"name","value",$("#submitRoleEdit").val()),
                                rels:auditArr
                            }),
                            success: function (data) {
                                if (data.code == 0) {
                                    tools.tableRefresh();
                                    toastrCog.success(data.msg, 1000)
                                } else {
                                    toastrCog.error(data.msg, 3000)
                                }
                                $("#editModal").modal("hide");
                            }
                        })
                    }
                }
            });
        },
        delModel: function () {
            $("#btnDel").on("click", function () {
                var selectArr = $("#myTable").bootstrapTable("getSelections");
                if (selectArr.length <= 0) {
                    toastrCog.error("请选择要删除的数据！", 3000);
                } else{
                    $("#delModal").modal("show");
                    $("#delName").html(
                        "确定要删除已创建的"+
                        "<span style='color:rgb(50, 136, 226)'>"+selectArr.length+"</span>"+
                        "条审批流程吗？");
                    $("#delModal").attr("data-id", tools.getStr(selectArr,"id"));
                }

            });
            $("#delBtn").on("click", function () {
                var id = $("#delModal").attr("data-id");
                $.ajax({
                    type: "post",
                    url: basePath + "/rest/approval/config-del",
                    dataType: "json",
                    data: {
                        ids: id
                    },
                    success: function (data) {
                        if (data.code == 0) {
                            tools.tableRefresh();
                            toastrCog.success(data.msg, 1000)
                        } else {
                            toastrCog.error(data.msg, 3000)
                        }
                        $("#delModal").modal("hide");
                    }
                })
            });
        },
        updataSelect: function ($obj, val) {
            $obj.val(val);
            $obj.trigger("chosen:updated");
        },
        getStr:function(selectArr,code){
            var str="";
            for (var i = 0; i < selectArr.length; i++) {
                str += selectArr[i][code] + ",";
            }
            str = str.substr(0, str.length - 1);
            return str;
        }
    };
    var draggables = { //模态框拖动
        init: function () {
            this.draggable($('#addModal'));
        },
        draggable: function (obj) {
            $(obj).draggable();
        }
    };
    //校验
    var validateFun = {
        init: function () {
            this.initKeyValidatorAdd();
            this.initKeyValidatorEdit();
        },
        initKeyValidatorAdd: function () {
            $("#addForm").jqxValidator({
                rules: [

                ],
                hintType: "label"
            });
        },
        initKeyValidatorEdit: function () {
            $("#editForm").jqxValidator({
                rules:[],
                hintType: "label"
            });
        }
    };
    var role={
        init:function(){
            role.addRole();
            role.removeRole();
            $(".auditRoleBox").on("click","input[type='radio']",function(){//点击集团后 审核次数终止
                var index= $(this).parents(".form-group").index();
                if($(this).val()=="0"){//点击集团
//                    $(this).parents(".form-group").find(".plusAddBtn").hide();
                    $(this).parents(".auditRoleBox").find(".form-group:gt("+index+")").each(function(){
                        $(this).find("input[type='radio'][value='0']").attr("checked",true);
                        $(this).find("input[type='radio']").attr("disabled",true);
                    })
                }else{//点击省内
                    if(index != (tools.maxPeopleLength-1)){
//                        $(this).parents(".form-group").find(".plusAddBtn").show();
                        if(index!=0){
//                            $(this).parents(".form-group").find(".minusBtn").show();
                        }
                    }
                    $(this).parents(".auditRoleBox").find(".form-group").eq(index+1).each(function(){
                        $(this).find("input[type='radio']").attr("disabled",false);
                    })
                }
            })
        },
        addRole:function(){
            $(".auditRoleBox").on("click",".plusAddBtn",function(){
                var box=$(this).parents(".auditRoleBox");
                role.appendRole(box);
                $(this).hide();
                $(this).parents(".form-group").find(".minusBtn").hide();
                if(parseInt(tools.maxPeopleLength)<= $(this).parents(".auditRoleBox").find(".form-group").length){
                    $(this).parents(".form-group").next().find(".plusAddBtn").hide();
                }
            })
        },
        appendRole:function(box,value,radioVal){
            var len=box.find(".form-group").length+1;
            var html='<div class="form-group">' +
                '<label for="" class="col-sm-3 control-label"><span class="fa fa-minus minusBtn"></span><span class="respan">*</span>'+len+'审批角色:</label>' +
                '<div class="col-sm-8">' +
                '<select class="form-control auditRoleAdd" name="code"></select><span class="fa fa-plus plusAddBtn"></span>' +
                '<div class="form-content radio_box">' +
                '<div class="radio"> <input type="radio" value="1" name="auditRole'+len+'" checked>省内</div>' +
                '<div class="radio"> <input type="radio" value="0" name="auditRole'+len+'">集团</div>' +
                '</div>' +
                '</div>' +
                '</div>';
            box.append(html);
            bs.selectDownNoDisabled(box.find(".form-group:last .auditRoleAdd"),tools.roleArr,"","100%");
            if(value){
                box.find(".form-group:last .auditRoleAdd").val(value).trigger("chosen:updated");
            }
            if(box.find(".form-group:last").prev().find("input[type='radio']:checked").val()=="0"){
                box.find(".form-group:last input[type='radio'][value='"+0+"']").attr("checked",true);
                box.find(".form-group:last").find("input[type='radio']").attr("disabled",true);
            }
            if(radioVal!=null){//渲染省份集团选中状态
                box.find(".form-group:last input[type='radio'][value='"+radioVal+"']").attr("checked",true);
            }
//            不是最后一个审批角色隐藏减号 加号
            var noLast=box.find(".form-group").not(".form-group:last");
            noLast.find(".plusAddBtn").hide();
            noLast.find(".minusBtn").hide();
//            如果审批角色个数正好等于最大审批数隐藏加号
            if(box.find(".form-group").length==tools.maxPeopleLength){
                box.find(".form-group .plusAddBtn").hide();
            }
//            如果审批角色是第一个 就隐藏  减号
            if(box.find(".form-group").length==1){
                box.find(".form-group").find(".minusBtn").hide();
            }
        },
        removeRole:function(){
            $(".auditRoleBox").on("click",".minusBtn",function(){
                var formGroup=$(this).parents(".form-group").prev();
                formGroup.find(".minusBtn").show();
                formGroup.find(".plusAddBtn").show();
                if($(this).parents(".auditRoleBox").find(".form-group").length==2){
                    $(this).parents(".auditRoleBox").find(".form-group").find(".minusBtn").hide();
                }
                $(this).parents(".form-group").remove();

            })
        }
    };
    $(function () {
        resize.init();
        tools.init();
        draggables.init();
        validateFun.init();
        var oTable = new TableInit();
        oTable.Init();
        role.init();
    })
</script>
</body>
</html>